package com.sumu.demo.cart;

import com.sumu.demo.entity.Fruit;
import com.sumu.demo.strategy.DiscountPromotionStrategy;
import com.sumu.demo.strategy.NoPromotionStrategy;
import com.sumu.demo.strategy.PromotionStrategy;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class ShoppingCart {
    private final Map<Fruit, Integer> shoppingItems = new HashMap<>();
    private PromotionStrategy promotionStrategy;

    public ShoppingCart() {
        this.promotionStrategy = new NoPromotionStrategy();
    }

    public void setPromotionStrategy(PromotionStrategy promotionStrategy) {
        this.promotionStrategy = promotionStrategy;
    }

    public void addFruit(Fruit fruit, int weight) {
        if (weight < 0) {
            throw new IllegalArgumentException("Purchase weight cannot be negative");
        }
        shoppingItems.put(fruit, weight);
    }

    public BigDecimal calculateOriginalAmount() {
        BigDecimal total = BigDecimal.ZERO;
        for (Map.Entry<Fruit, Integer> entry : shoppingItems.entrySet()) {
            Fruit fruit = entry.getKey();
            int weight = entry.getValue();
            total = total.add(fruit.getPricePerJin().multiply(new BigDecimal(weight)));
        }
        return total;
    }

    public BigDecimal calculateFinalAmount() {
        if (promotionStrategy instanceof DiscountPromotionStrategy) {
            // 调用带购物项的折扣计算方法
            return ((DiscountPromotionStrategy) promotionStrategy).calculateDiscountAmount(shoppingItems);
        } else {
            BigDecimal originalAmount = calculateOriginalAmount();
            return promotionStrategy.calculatePromotionAmount(originalAmount);
        }
    }

    public void clearCart() {
        shoppingItems.clear();
    }
}